<template>
  <view class="zmt-multiple-upload-images">
    <!-- 图片展示区域 -->
    <view class="image-list">
      <!-- 已上传图片 -->
      <view v-for="(item, index) in imageList" :key="item.fileID" class="image-item">
        <image :src="item.url" mode="aspectFill" class="image"></image>
        <view class="delete-btn" @click="deleteImage(index)">
          <uni-icons type="close" size="16" color="#fff"></uni-icons>
        </view>
      </view>
      
      <!-- 上传按钮 -->
      <view v-if="imageList.length < maxCount" class="upload-btn" @click="chooseImage">
        <uni-icons type="plus" size="30" color="#999"></uni-icons>
        <text class="upload-text">点击上传</text>
      </view>
    </view>
    
    <!-- 上传进度条 -->
    <view v-if="uploading" class="progress-container">
      <progress :percent="uploadProgress" stroke-width="3" activeColor="#007aff" class="progress"></progress>
      <text class="progress-text">{{ uploadProgress }}%</text>
    </view>
  </view>
</template>

<script>
export default {
  name: 'zmt-multiple-upload-images',
  props: {
    // 最多上传图片数量
    maxCount: {
      type: Number,
      default: 9
    },
    // 已上传图片列表，用于数据回显
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 图片列表
      imageList: [],
      // 是否正在上传
      uploading: false,
      // 上传进度
      uploadProgress: 0
    };
  },
  watch: {
    // 监听value变化，更新图片列表
    value: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal)) {
          this.imageList = [...newVal];
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 选择图片
    chooseImage() {
      const that = this;
      // 计算还可以选择的图片数量
      const count = this.maxCount - this.imageList.length;
      
      if (count <= 0) {
        uni.showToast({
          title: '已达到最大上传数量',
          icon: 'none'
        });
        return;
      }
      
      // 选择图片
      uni.chooseImage({
        count: count,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          // 上传图片
          that.uploadImages(res.tempFilePaths);
        }
      });
    },
    
    // 上传图片
    uploadImages(filePaths) {
      const that = this;
      const uploadTasks = [];
      
      // 遍历选择的图片进行上传
      filePaths.forEach((filePath, index) => {
        const uploadTask = that.uploadSingleImage(filePath, index, filePaths.length);
        uploadTasks.push(uploadTask);
      });
      
      // 等待所有图片上传完成
      Promise.all(uploadTasks).then(() => {
        that.uploading = false;
        that.uploadProgress = 0;
        // 向父组件发送上传完成的事件
        that.$emit('change', that.imageList);
      }).catch(error => {
        console.error('上传失败:', error);
        that.uploading = false;
        that.uploadProgress = 0;
        uni.showToast({
          title: '部分图片上传失败',
          icon: 'none'
        });
      });
    },
    
    // 生成UUID
    generateUUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    },
    
    // 获取文件扩展名
    getFileExtension(filePath) {
      const match = filePath.match(/\.(\w+)$/);
      return match ? match[1] : 'jpg'; // 默认使用jpg扩展名
    },
    
    // 上传单张图片
    uploadSingleImage(filePath, index, total) {
      const that = this;
      
      return new Promise((resolve, reject) => {
        // 生成文件名（使用UUID）
        const uuid = that.generateUUID();
        const extension = that.getFileExtension(filePath);
        const fileName = `image_${uuid}.${extension}`;
        
        // 显示上传进度
        that.uploading = true;
        
        // 上传到uniCloud
        uniCloud.uploadFile({
          cloudPath: fileName,
          filePath: filePath,
          success: res => {
            // 上传成功，添加到图片列表
            const imageInfo = {
              url: res.fileID,
              fileID: res.fileID
            };
            
            that.imageList.push(imageInfo);
            
            // 更新上传进度
            that.uploadProgress = Math.floor(((index + 1) / total) * 100);
            
            resolve(res);
          },
          fail: err => {
            console.error('上传失败:', err);
            reject(err);
          }
        });
      });
    },
    
    // 删除图片
    deleteImage(index) {
      const that = this;
      
      uni.showModal({
        title: '提示',
        content: '确定要删除这张图片吗？',
        success(res) {
          if (res.confirm) {
            // 从列表中删除
            that.imageList.splice(index, 1);
            // 向父组件发送变化事件
            that.$emit('change', that.imageList);
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.zmt-multiple-upload-images {
  width: 100%;
}

.image-list {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  gap: 10px;
  padding-bottom: 10px;
  -webkit-overflow-scrolling: touch; /* 增加滚动流畅度 */
}

/* 隐藏滚动条但保留功能 */
.image-list::-webkit-scrollbar {
  display: none;
}

.image-item {
  position: relative;
  width: 300px;
  height: 300px;
  border-radius: 8rpx;
  overflow: hidden;
  flex-shrink: 0; /* 防止图片被压缩 */
  border:1px dashed #eee;
  margin-left:5px;
  margin-right:5px;
}

.image {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持图片比例并填满容器 */
}

.delete-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 36rpx;
  height: 36rpx;
  background-color: rgba(255, 0, 0, 0.7);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor:pointer;
}

.upload-btn {
  width: 300px;
  height: 300px;
  border: 1px dashed #ddd;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f9f9f9;
  flex-shrink: 0; /* 防止按钮被压缩 */
}

.upload-text {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.progress-container {
  margin-top: 20rpx;
  padding: 0 20rpx;
}

.progress {
  width: 100%;
}

.progress-text {
  font-size: 24rpx;
  color: #666;
  text-align: center;
  margin-top: 10rpx;
}
</style>